const User = require('../models/User');
const { ROLES, ROLE_LEVELS, ROLE_NAMES } = require('../constants/roles');
const XLSX = require('xlsx');

class UserService {
  // 用户登录
  static async login(username, password) {
    const user = await User.findOne({ username });
    
    if (!user || user.password !== password) {
      throw new Error('用户名或密码错误');
    }

    const userInfo = user.toObject();
    delete userInfo.password;
    return userInfo;
  }

  // 用户注册
  static async register(userData) {
    const { username, password, email, phone, nickname, role } = userData;

    // 检查用户名唯一性
    if (await User.findOne({ username })) {
      throw new Error('用户名已存在');
    }

    // 检查邮箱唯一性
    if (email && await User.findOne({ email })) {
      throw new Error('邮箱已被使用');
    }

    // 检查手机号唯一性
    if (phone && await User.findOne({ phone })) {
      throw new Error('手机号已被使用');
    }

    const newUser = new User({
      username,
      password,
      email: email || undefined,
      phone: phone || undefined,
      nickname: nickname || username,
      role: role || 'user',
      roleName: ROLE_NAMES[role] || '普通用户',
      status: 1
    });

    return await newUser.save();
  }

  // 获取用户列表
  static async getUsers(queryParams) {
    const { 
      username,
      phone,
      email,
      role,
      status,
      createTime,
      updateTime,
      page = 1,
      pageSize = 10,
      sortBy = 'createTime:desc'
    } = queryParams;

    const query = {};
    if (username) query.username = username;
    if (phone) query.phone = phone;
    if (email) query.email = email;
    if (role) query.role = role;
    if (status) query.status = parseInt(status);
    if (createTime) query.createTime = createTime;
    if (updateTime) query.updateTime = updateTime;

    const [sortField, sortOrder] = sortBy.split(':');
    const sortOptions = { 
      [sortField]: sortOrder === 'desc' ? -1 : 1 
    };

    const [users, total] = await Promise.all([
      User.find(query)
        .select('-password -__v')
        .sort(sortOptions)
        .skip((page - 1) * pageSize)
        .limit(pageSize)
        .lean(),
      User.countDocuments(query)
    ]);

    return {
      list: users,
      pagination: {
        total,
        page: parseInt(page),
        pageSize: parseInt(pageSize),
        totalPages: Math.ceil(total / pageSize)
      }
    };
  }

  // 更新用户信息
  static async updateUser(userId, updateData) {
    const user = await User.findById(userId);
    
    if (!user) {
      throw new Error('用户不存在');
    }

    // 检查邮箱唯一性
    if (updateData.email) {
      const emailExists = await User.findOne({ 
        email: updateData.email, 
        _id: { $ne: userId } 
      });
      if (emailExists) {
        throw new Error('邮箱已被其他用户使用');
      }
    }

    // 检查手机号唯一性
    if (updateData.phone) {
      const phoneExists = await User.findOne({ 
        phone: updateData.phone, 
        _id: { $ne: userId } 
      });
      if (phoneExists) {
        throw new Error('手机号已被其他用户使用');
      }
    }

    // 更新字段
    Object.assign(user, updateData);
    user.updateTime = new Date();

    await user.save();
    return user;
  }

  // 获取用户信息
  static async getUserProfile(username) {
    const user = await User.findOne({ username })
      .select('-password -__v');
    
    if (!user) {
      throw new Error('用户不存在');
    }
    return user;
  }

  // 删除用户
  static async deleteUser(userId, currentUser) {
    const operator = await User.findOne({ username: currentUser.username });
    const userToDelete = await User.findById(userId);
    
    if (!userToDelete) {
      throw new Error('用户不存在');
    }

    if (userToDelete._id.toString() === operator._id.toString()) {
      throw new Error('不能删除自己的账号');
    }

    if (userToDelete.role === 'admin') {
      throw new Error('不能删除其他管理员账号');
    }

    await User.deleteOne({ _id: userId });
  }

  // 获取所有角色
  static async getRoles() {
    return Object.entries(ROLES).map(([key, value]) => ({
      code: value,
      name: ROLE_NAMES[value],
      level: ROLE_LEVELS[value]
    }));
  }

  // 导出用户数据
  static async exportUsers(ids) {
    const idArray = ids.split(',');
    const users = await User.find({ _id: { $in: idArray } })
      .select('-password -__v')
      .lean();
    
    console.log(users);
    
    const formattedUsers = users.map(user => ({
      ID: user._id.toString(),
      用户名: user.username,
      邮箱: user.email || '',
      手机号: user.phone || '',
      昵称: user.nickname || user.username,
      角色: user.role || 'user',
      状态: user.status === 1 ? '正常' : '禁用',
      创建时间: user.createTime || new Date().toISOString(),
      更新时间: user.updateTime || user.createTime || new Date().toISOString(),
      最近登录时间: user.lastLoginTime || '',
      最近登录IP: user.lastLoginIp || ''
    }));

    const worksheet = XLSX.utils.json_to_sheet(formattedUsers);
    worksheet['!cols'] = [
      { wpx: 80 }, { wpx: 100 }, { wpx: 200 }, { wpx: 120 }, 
      { wpx: 100 }, { wpx: 80 }, { wpx: 80 }, { wpx: 150 },
      { wpx: 150 }, { wpx: 150 }, { wpx: 150 }
    ];

    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, '用户列表');
    return XLSX.write(workbook, { bookType: 'xlsx', type: 'buffer' });
  }
}

module.exports = UserService;
